package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: TODO(文件上传)
 * @Author da
 * @Date 2021/8/16 下午 6:33
 */
@RestController
@RequestMapping("/files")
public class FileController
{
    //    端口
    @Value("${server.port}")
    private String port;
    //    ip
    private final String ip = "http://localhost";

    //    文件上传
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file)
    {
//        获取文件名称
        String filename = file.getOriginalFilename();
//        定义文件的唯一标识(前缀)
        String uuid = IdUtil.fastSimpleUUID();
//        获取当前项目的根路径System.getProperty("user.dir")
        String rootFilePath = System.getProperty("user.dir") + "/demo/src/main/resources/files/" + uuid + "_" + filename;
        try
        {
//            使用工具类写入文件
            FileUtil.writeBytes(file.getBytes(), rootFilePath);
            //返回结果url,用返回的url发起get请求就会调用下面的文件下载接口,返回数据
            return Result.success(ip + ":" + port + "/files/" + uuid);
        } catch (IOException e)
        {
            return Result.error("-1", "文件上传失败" + e.getMessage());
        }

    }

    //    文件下载
    @GetMapping("/{flag}")
    public void getFiles(HttpServletResponse response, @PathVariable String flag)
    {
        OutputStream os;
        String basePath = System.getProperty("user.dir") + "/demo/src/main/resources/files/";
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");

        try
        {
            if (StrUtil.isNotEmpty(avatar))
            {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
